<?php

class pub extends CI_Model
{
    //统一日志
    function log_base($nr = '', $mid = '', $name = '')
    {
        if (!$this->config->item('admin')) {
            show_error('The system has been shut down, please contact the engineer.<br><br>EMAIL : a@72zu.com');
        }
        $this->load->library('user_agent');
        $da['name'] = $this->session->userdata('name') ? $this->session->userdata('name') : $name;
        $da['xid'] = $this->session->userdata('sid') ? $this->session->userdata('sid') : 0;
        $da['mid'] = $this->session->userdata('midx') ? $this->session->userdata('midx') : $this->session->userdata('mid');
        $da['mid'] = $da['mid'] ? $da['mid'] : $mid;
        $da['nr'] = $nr;
        $da['shop_id'] = 0;
        $da['duan'] = $this->agent->is_mobile() ? 1 : 2;
        $da['is_robot'] = $this->agent->is_robot() ? 1 : 2;

        $da['browser'] = $this->agent->browser();
        $da['platform'] = $this->agent->platform();
        $da['mobile'] = $this->agent->mobile();
        $da['robot'] = $this->agent->robot();

        $da['log_mkip'] = $this->input->ip_address();
        $da['log_del'] = 1;
        $da['log_mktime'] = mktime();

        $this->db->insert('log', $da);
    }

//后端日志
    function logp($nr, $state, $md = '')
    {

        if ((@mktime() - $this->session->userdata('lastmktime')) > 36000) {
            if (!$this->input->is_ajax_request()) {
                redirect('/iadmin/login/suop');
            } else {
                $this->session->sess_destroy();
                echo json_encode(array('ajax_out' => 1));
            }
        } else {
            if ($this->input->is_ajax_request()) {
                $this->session->set_userdata('lastmktime', @mktime());
            }
            if (!$this->session->userdata('sin')) {
                redirect('/iadmin/login');
            } else {
                $this->db->select('state,type,ly');
                $q = $this->db->get_where('staff', array('staff_id' => $this->session->userdata('sid')));
                $m = $q->row_array(0);
                $states = explode('-', $state);
                if (in_array($m['state'], $states)) {
                    if ($m['type'] == 2) {
                        $this->db->update('staff', array('type' => 1), array('staff_del' => 1, 'staff_id' => $this->session->userdata('sid')));
                        $this->session->sess_destroy();
                        if (!$this->input->is_ajax_request()) {
                            redirect('/iadmin/login');
                        } else {
                            echo json_encode(array('ajax_out' => 1));
                        }
                    } elseif ($m['type'] == 3) {
                        $this->session->sess_destroy();
                        show_error('Your account has been deactivated.');
                    } else {
                        //模块授权
                        if ($md) {
                            if ($this->config->item($md)) {
                                $this->log_base($nr);
                            } else {
                                show_error('Your account has been deactivated.');
                            }
                        } else {
                            $this->log_base($nr);
                        }
                    }
                } else {
                    show_error('You have no right to access the module.');
                }
            }
        }
    }

//前端日志
    function logq($nr = '', $md = '')
    {
        if ($this->session->userdata('min')) {
            //检测会员权限
            $this->db->select('type,mid,openid');
            $q = $this->db->get_where('member', array('mid' => $this->session->userdata('mid')));
            if ($q->num_rows() > 0) {
                $ls = $q->row_array();
                if ($ls['type'] == 4) {
                    show_error('Your account has been deactivated.');
                } else {
                    //把消息同步到app服务器
                    $this->up_app($ls);
                }
            } else {
                redirect('shop/out');
            }

            if ($md) {
                if ($this->config->item($md)) {
                    $this->log_base($nr);
                } else {
                    show_error('Your account has been deactivated.');
                }
            } else {
                $this->log_base($nr);
            }
        } else {
            if ($nr != '微信验证') {
                if ($this->input->get('mid')) {
                    $this->session->set_userdata('tj_mid', $this->input->get('mid'));
                }
                //通过token模拟登陆
                if ($this->input->get('token')) {
                    $this->db->select('mid,headimgurl,type');
                    $q = $this->db->get_where('member', array('token' => $this->input->get('token')));
                    if ($q->num_rows() > 0) {
                        $m = $q->row_array(0);
                        if ($m['type'] == 4) {
                            show_error('Your account has been deactivated.');
                        } else {
                            $s['is_app'] = TRUE;
                            $s['mid'] = $m['mid'];
                            $s['min'] = TRUE;
                            $s['head'] = $m['headimgurl'];
                            $this->session->set_userdata($s);
                        }
                    } else {
                        show_error('Verification code does not exist.');
                    }
                } else {
                    $ls = $this->config->item('base_urlx');
                    $redirect_uri = $ls . '/wx_reg/wx_login/';
                    $wechat_redirect = 'lance';
                    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->config->item('wxAppId') . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=' . $wechat_redirect . '#wechat_redirect';
                    //记录当前url 然后跳转
                    $this->load->helper('url');
                    $this->session->set_userdata('ls_url', site_url(uri_string()));
                    redirect($url);
                }
            }
        }
    }


    //普通上传
    function _up($name, $ys = TRUE)
    {
        $error = "";
        $fileElementName = $name;
        $config['upload_path'] = './upfiles/ls/';
        $config['allowed_types'] = 'gif|jpg|JPG|png|amr|bmp|wav';
        $config['encrypt_name'] = TRUE;
        $config['file_name'] = date("YmdHis");
        if (!file_exists($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, true);
        }
        $this->load->library('upload', $config);
        if ($this->upload->do_upload($fileElementName)) {
            $datax = $this->upload->data();
            $data['name'] = $datax['client_name'];
            $data['url'] = date('Y-m-d') . '/' . $datax['raw_name'];
            $data['file'] = $datax['file_ext'];
            $data['mid'] = $this->session->userdata('xid');
            $data['upfile_mktime'] = mktime();
            $data['upfile_uptime'] = mktime();
            $data['upfile_mkip'] = $this->input->ip_address();
            $data['upfile_upip'] = $this->input->ip_address();
            $this->db->insert('upfile', $data);
            $data['id'] = $this->db->insert_id();
            if ($ys) {
                $this->load->library('image_lib');
                //生产缩略图
                unset($config);
                $config['image_library'] = 'gd2';
                $config['source_image'] = $datax['full_path'];
                $config['create_thumb'] = TRUE;
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 400;
                $config['height'] = 400;
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
                $data['error'] = '';
            }
            $this->oss_up($datax, $ys);
        } else {
            $data['error'] = '上传失败!' . $this->upload->display_errors();
        }
        //$data['is_image'] = $datax['is_image'];
        return $data;
    }

    //oss上传
    function oss_up($data, $ys)
    {
        if (!defined('DS')) {
            define('DS', DIRECTORY_SEPARATOR);
        }
        require_once(FCPATH . APPPATH . 'third_party' . DS . 'oss' . DS . 'sdk.class.php');
        $obj = new ALIOSS();
        $obj->set_debug_mode(FALSE);
        try {
            //创建目录
            $response = $obj->create_object_dir($this->config->item('oss_path'), date('Y-m-d'));
            //上传文件
            $options = array(ALIOSS::OSS_FILE_UPLOAD => $data['full_path'], 'partSize' => $data['file_size']);
            $da = date('Y-m-d') . '/' . $data['file_name'];
            $response = $obj->create_mpu_object($this->config->item('oss_path'), $da, $options);
            if ($ys) {
                //上传缩略图
                $options = array(ALIOSS::OSS_FILE_UPLOAD => $data['file_path'] . $data['raw_name'] . '_thumb' . $data['file_ext'], 'partSize' => getimagesize($data['file_path'] . $data['raw_name'] . '_thumb' . $data['file_ext']));
                $da = date('Y-m-d') . '/' . $data['raw_name'] . '_thumb' . $data['file_ext'];
                $response = $obj->create_mpu_object($this->config->item('oss_path'), $da, $options);
                //删除临时图片
                @unlink($data['file_path'] . $data['raw_name'] . '_thumb' . $data['file_ext']);
            }
            @unlink($data['full_path']);
        } catch (Exception $ex) {
            die($ex->getMessage());
        }
    }

    function oss_dz($dz, $thumb = true)
    {
        if (strpos($dz, '_thumb') === false && $dz && $thumb) {
            $ls = explode('.', $dz);
            $dz = $ls[0] . '_thumb.' . $ls[1];
        }
        $da = 'http://' . $this->config->item('oss_path') . '.oss-cn-hangzhou.aliyuncs.com/' . $dz;
        return $da;

    }

    function is_object_exist()
    {
        if (!defined('DS')) {
            define('DS', DIRECTORY_SEPARATOR);
        }
        require_once(FCPATH . APPPATH . 'third_party' . DS . 'oss' . DS . 'sdk.class.php');
        $obj = new ALIOSS();
        $obj->set_debug_mode(FALSE);
        $response = $obj->is_object_exist($this->config->item('oss_path'), '2013-12-04/de41aa2b69c62de402984d111119032799d85_thumb.jpg');
        $this->oss_format($response);
    }

    function oss_del($dz)
    {
        if (!defined('DS')) {
            define('DS', DIRECTORY_SEPARATOR);
        }
        require_once(FCPATH . APPPATH . 'third_party' . DS . 'oss' . DS . 'sdk.class.php');
        $obj = new ALIOSS();
        $obj->set_debug_mode(FALSE);
        try {
            $da = $obj->delete_object($this->config->item('oss_path'), $dz);
            return $da;
        } catch (Exception $ex) {
            die($ex->getMessage());
        }
    }

    //oss测试
    function oss_format($response)
    {
        echo '|-----------------------Start---------------------------------------------------------------------------------------------------' . "\n";
        echo '|-Status:' . $response->status . "\n";
        echo '|-Body:' . "\n";
        echo $response->body . "\n";
        echo "|-Header:\n";
        print_r($response->header);
        echo '-----------------------End-----------------------------------------------------------------------------------------------------' . "\n\n";
    }

    //获取token
    function access_token()
    {
        //获取数据
        $this->db->order_by('id', 'desc');
        $this->db->limit(1);
        $q = $this->db->get_where('access_token');
        if ($q->num_rows() > 0) {
            $access_token = $q->row_array(0);
            if ((mktime() - $access_token['mktime']) < ($access_token['expires_in'] - 500)) {
                $back['access_token'] = $access_token['access_token'];
                $back['jsapi_ticket'] = $access_token['jsapi_ticket'];
            } else {
                $back = $this->get_access_token();
            }
        } else {
            $back = $this->get_access_token();
        }
        $back['type'] = TRUE;
        return $back;
    }

    function get_access_token()
    {
        $da['error'] = '';
        $da['type'] = TRUE;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->config->item('wxAppId') . '&secret=' . $this->config->item('wxAppSecret');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            $da['error'] = 'Errno' . curl_error($ch);
            $da['type'] = FALSE;
        }
        curl_close($ch);
        $postObj = json_decode($tmpInfo);
        $da['access_token'] = $postObj->access_token;

        $dax['access_token'] = $da['access_token'];
        $dax['mktime'] = mktime();
        $dax['expires_in'] = $postObj->expires_in - 100;
        //获取jsapi_ticket
        $ls = file_get_contents('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $postObj->access_token . '&type=jsapi');
        $js = json_decode($ls, true);
        $da['jsapi_ticket'] = $js['ticket'];
        $dax['jsapi_ticket'] = $da['jsapi_ticket'];

        $this->db->insert('access_token', $dax);

        return $da;
    }

    //更新微信信息
    function upset_member($openid)
    {
        $access_token = $this->access_token();
        if ($access_token['type']) {
            $a = file_get_contents('https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token['access_token'] . '&openid=' . $openid . '&lang=zh_CN');
            $m = json_decode($a, true);
            if ($m['openid']) {
                $da['subscribe'] = $m['subscribe'];
                $da['openid'] = $m['openid'];
                $da['nickname'] = $m['nickname'];
                $da['sex'] = $m['sex'];
                $da['city'] = $m['city'];
                $da['country'] = $m['country'];
                $da['province'] = $m['province'];
                $da['language'] = $m['language'];
                $da['headimgurl'] = $m['headimgurl'];

                $da['unionid'] = $m['unionid'] ? $m['unionid'] : '';

                //1普通用户 2分销商 3禁言
                $da['type'] = 1;
                //判断id是否存在
                $q = $this->db->get_where('member', array('openid' => $da['openid']));
                if ($q->num_rows() > 0) {
                    unset($da['type']);
                    if ($da['nickname']) {
                        $this->db->update('member', $da, array('openid' => $da['openid']));
                    }
                } else {
                    $da['tj_mid'] = $this->config->item('tj_mid');
                    $da['subscribe_time'] = mktime();
                    $this->db->insert('member', $da);
                    $da['mid'] = $this->db->insert_id();
                }
                return $da;
            } else {
                return FALSE;
            }
        }
    }

    //获取用户信息  $sx 是否更新数据库信息
    function get_member($openid, $sx = false)
    {
        $q = $this->db->get_where('member', array('openid' => $openid));
        if ($q->num_rows() > 0) {
            if ($sx) {
                return $this->upset_member($openid);
            } else {
                $da = $q->row_array(0);
                return $da;
            }
        } else {
            return $this->upset_member($openid);
        }
    }

    //无限缓存
    function wx_cache($mid, $fid = 0, $lv = 1)
    {
        if ($fid == 0) {
            $this->db->select('tj_mid');
            $q = $this->db->get_where('member', $mid);
            $tj = $q->row_array(0);
            $fid = $tj['tj_mid'];
        } else {
            $this->db->select('tj_mid');
            $q = $this->db->get_where('member', $fid);
            $tj = $q->row_array(0);
            $fid = $tj['tj_mid'];
        }

        if ($fid > 0) {
            //入库
            $q = $this->db->get_where('wx_cache', array('mid' => $mid, 'lv' => $lv));
            if ($q->num_rows() == 0) {
                $da['mid'] = $mid;
                $da['lv'] = $lv;
                $da['fid'] = $tj['tj_mid'];
                $da['mktime'] = mktime();
                $da['did'] = $da['mid'] . '-' . $da['fid'];
                $this->db->insert('wx_cache', $da);
                if ($fid != $this->config->item('tj_mid')) {
                    $lv++;
                    $this->wx_cache($mid, $fid, $lv);
                }
            }
        }
    }

    function get_yz_url($url)
    {
        $redirect_uri = $this->config->item('base_urlx') . '/wx_reg/wx_login';
        $wechat_redirect = $this->config->item('base_urlx') . $url;
        return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->config->item('wxAppId') . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_base&state=' . $wechat_redirect . '#wechat_redirect';
    }

    //获取二维码 1会员 2商品 3文字 4机构 5订单提货(扫一扫成为管理员) 6报名  7管理员登陆
    function get_ewm($idx, $type = 1)
    {
        $da['dx_id'] = $idx;
        $da['type'] = $type;
        $pd = $this->db->get_where('ewm', $da);
        if ($pd->num_rows() > 0) {
            $ls = $pd->row_array(0);
            return $this->get_er($ls['ewm_id']);
        } else {
            $this->db->insert('ewm', $da);
            $id = $this->db->insert_id();
            return $this->get_er($id);
        }
    }

    //获取推广的二维码 QR_SCENE QR_LIMIT_SCENE
    function get_er($scene_id, $type = 'QR_SCENE')
    {
        $this->load->helper('url');
        $this->log_base('获取二维码');
        $access_token = $this->access_token();
        $data = '{"expire_seconds": 2592000, "action_name": "' . $type . '", "action_info": {"scene": {"scene_id":' . $scene_id . '}}}';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $access_token['access_token']);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        $nr = json_decode($tmpInfo, TRUE);
        curl_close($ch);
        return 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($nr['ticket']);
    }

    //发送主动信息
    function send_zd_text($openid = '', $text)
    {
        $access_token = $this->access_token();
        $data = '{"touser":"' . $openid . '","msgtype":"text","text":{"content":"' . $text . '"}}';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $access_token['access_token']);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);

        curl_close($ch);
    }

    //发送主动图片
    function send_zd_img($openid = '', $meid)
    {
        $this->load->helper('url');
        $access_token = $this->access_token();
        $data = '{"touser":"' . $openid . '","msgtype":"image","image":{"media_id":"' . $meid . '"}}';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $access_token['access_token']);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        curl_close($ch);
    }

    function send_zd_voice($openid = '', $meid)
    {
        $this->load->helper('url');
        $access_token = $this->access_token();
        $data = '{"touser":"' . $openid . '","msgtype":"voice","voice":{"media_id":"' . $meid . '"}}';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $access_token['access_token']);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        curl_close($ch);
    }


    function uploadMedia($url, $file)
    {
        //要上传的文件
        $fields['media'] = '@' . $file;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            return curl_error($ch);
        }
        curl_close($ch);
        $back = json_decode($result);
        return $back;
    }

//redis
    function getRedis()
    {
        static $redis;
        if (empty($redis)) {
            $redis = new Redis();
            $redis->connect('r-bp12adb5da21cc44.redis.rds.aliyuncs.com', 6379);
            $redis->auth('Pan123456');
        }
        return $redis;
    }

//发送客服信息
    function send_dkf_zd($openid, $kf_account)
    {
        if (!$kf_account) {
            $this->db->limit(1);
            $this->db->order_by('qz', 'asc');
            $q = $this->db->get_where('plug_kf', array('status >' => 0));
            $m = $q->row_array(0);

            $this->db->update('plug_kf', array('qz' => ($m['qz'] + 1)), array('id' => $m['id']));
            $kf_account = $m['kf_account'];
        }

        $access_token = $this->access_token();
        $url = 'https://api.weixin.qq.com/customservice/kfsession/create?access_token=' . $access_token['access_token'];

        $data = '{"kf_account":"' . $kf_account . '","openid":"' . $openid . '","text":"新注册用户"}';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);

        curl_close($ch);
    }

    //快速购买商品
    function k_buy($sp, $m, $numb = 1, $zflx = 'js', $ad_id = 0)
    {
        $da['mid'] = $m['mid'];
        $da['tj_mid'] = $m['tj_mid'];
        $da['zffs'] = 0;
        $da['name'] = $m['name'] ? $m['name'] : $m['nickname'];
        $da['phone'] = $m['phone'];
        $da['dq'] = $m['country'] . '-' . $m['province'] . '-' . $m['city'];
        $da['zz'] = $m['zz'];
        $da['ly'] = '快速下单';
        $da['use_jb'] = 2;
        $da['is_jp'] = 1;
        $da['state'] = 0;
        $da['zfzt'] = 1;

        $da['thshop'] = 0;
        $da['thfs'] = $sp['xffs'];

        $da['mktime'] = mktime();
        $da['mkip'] = $this->input->ip_address();

        //设置app的支付类型
        if ($this->session->userdata('is_app')) {
            $da['zflx'] = 1;
        }
        echo "<pre>";
        $this->db->insert('bill', $da);

        $bill_id = $this->db->insert_id();

        $bill_item['sp_id'] = $sp['sp_id'];
        $bill_item['sp_name'] = $sp['name'];

        $bill_item['sp_price'] = $sp['price'];

        //留意商品价格 红包等
        $bill_item['sp_dl'] = $sp['dl'];
        $bill_item['sp_dl1'] = $sp['dl1'];
        $bill_item['sp_dl2'] = $sp['dl2'];
        $bill_item['sp_lq'] = $sp['lq'];

        $bill_item['numb'] = $numb;

        $bill_item['sp_color'] = '';

        $bill_item['je'] = $bill_item['numb'] * ($bill_item['sp_price'] - $sp['lq']);

        $je = $bill_item['je'];

        $bill_item['bill_id'] = $bill_id;
        $bill_item['mid'] = $m['mid'];
        $bill_item['tj_mid'] = $m['tj_mid'];
        $this->db->insert('bill_item', $bill_item);

        //更新订单情况
        $this->db->update('bill', array('je' => $je, 'numb' => $numb), array('bill_id' => $bill_id));

        if (intval($ad_id) > 0) {
            $this->db->update('jdz_ad', array('bill_id' => $bill_id), array('id' => $ad_id));
        }


        //跳转到支付
        $url = '/wx_pay/ddzf/' . $bill_id . '?zflx=' . $zflx;
        redirect($url);
    }

    //快钱的快速购买
    function kq_buy($sp, $m, $numb = 1, $zflx = 'js')
    {
        $da['mid'] = $m['mid'];
        $da['tj_mid'] = $m['tj_mid'];
        $da['zffs'] = 0;
        $da['name'] = $m['name'] ? $m['name'] : $m['nickname'];
        $da['phone'] = $m['phone'];
        $da['dq'] = $m['country'] . '-' . $m['province'] . '-' . $m['city'];
        $da['zz'] = $m['zz'];
        $da['ly'] = '快速下单';
        $da['use_jb'] = 2;
        $da['is_jp'] = 1;
        $da['state'] = 0;
        $da['zfzt'] = 1;

        $da['thshop'] = 0;
        $da['thfs'] = $sp['xffs'];

        $da['mktime'] = mktime();
        $da['mkip'] = $this->input->ip_address();

        //设置app的支付类型
        if ($this->session->userdata('is_app')) {
            $da['zflx'] = 1;
        }

        $this->db->insert('bill', $da);
        $bill_id = $this->db->insert_id();

        $bill_item['sp_id'] = $sp['sp_id'];
        $bill_item['sp_name'] = $sp['name'];

        $bill_item['sp_price'] = $sp['price'];

        //留意商品价格 红包等
        $bill_item['sp_dl'] = $sp['dl'];
        $bill_item['sp_dl1'] = $sp['dl1'];
        $bill_item['sp_dl2'] = $sp['dl2'];
        $bill_item['sp_lq'] = $sp['lq'];

        $bill_item['numb'] = $numb;

        $bill_item['sp_color'] = '';

        $bill_item['je'] = $bill_item['numb'] * ($bill_item['sp_price'] - $sp['lq']);

        $je = $bill_item['je'];

        $bill_item['bill_id'] = $bill_id;
        $bill_item['mid'] = $m['mid'];
        $bill_item['tj_mid'] = $m['tj_mid'];
        $this->db->insert('bill_item', $bill_item);

        //更新订单情况
        $this->db->update('bill', array('je' => $je, 'numb' => $numb), array('bill_id' => $bill_id));

        //跳转到支付
        $url = '/kqpay/do_pay/' . $bill_id;

        redirect($url);
    }

    //判断是否购买了某款商品
    function pd_gm($sp_id, $mid = 0)
    {
        $pd = FALSE;
        $mid = $mid ? $mid : $this->session->userdata('mid');
        $this->db->where('state >', 0);
        $this->db->where('bill_id in(select bill_id from pan_bill_item where sp_id=' . $sp_id . ')');
        $q = $this->db->get_where('bill', array('mid' => $mid));
        if ($q->num_rows() > 0) {
            $pd = TRUE;
        }
        return $pd;
    }

    function get_setting($title = '', $en = '')
    {
        $q = $this->db->get_where('setting');
        $da['setting'] = $q->row_array(0);
        $da['title'] = $title;
        $da['en'] = $en;
        return $da;
    }

    //统计
    function get_jb_tj($type, $date1 = 0, $date2 = 0)
    {
        $this->db->select('sum(je)');

        if ($date1) {
            $date1 = strtotime($date1);
            $this->db->where('mktime >', $date1);
        }

        if ($date2) {
            $date2 = strtotime($date2 . ' 23:59:59');
            $this->db->where('mktime <', $date2);
        }

        $q = $this->db->get_where('jb', array('type' => $type));
        $ls = $q->row_array(0);
        return $ls['sum(je)'] > 0 ? $ls['sum(je)'] : '0';
    }

}

?>
